<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>物联网卡年费订单测试</title>
    <style>
        body {
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            max-width: 800px;
            margin: 0 auto;
            padding: 20px;
            background-color: #f5f5f5;
        }
        .container {
            background: white;
            padding: 30px;
            border-radius: 10px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
        }
        h1 {
            color: #333;
            text-align: center;
            margin-bottom: 30px;
        }
        .test-section {
            margin-bottom: 30px;
            padding: 20px;
            border: 1px solid #ddd;
            border-radius: 8px;
            background-color: #fafafa;
        }
        .test-section h3 {
            color: #555;
            margin-top: 0;
        }
        button {
            background-color: #007bff;
            color: white;
            border: none;
            padding: 10px 20px;
            border-radius: 5px;
            cursor: pointer;
            margin: 5px;
            font-size: 14px;
        }
        button:hover {
            background-color: #0056b3;
        }
        button:disabled {
            background-color: #ccc;
            cursor: not-allowed;
        }
        .result {
            margin-top: 15px;
            padding: 15px;
            border-radius: 5px;
            white-space: pre-wrap;
            font-family: monospace;
            font-size: 12px;
            max-height: 300px;
            overflow-y: auto;
        }
        .success {
            background-color: #d4edda;
            border: 1px solid #c3e6cb;
            color: #155724;
        }
        .error {
            background-color: #f8d7da;
            border: 1px solid #f5c6cb;
            color: #721c24;
        }
        .info {
            background-color: #d1ecf1;
            border: 1px solid #bee5eb;
            color: #0c5460;
        }
        input, select {
            width: 100%;
            padding: 8px;
            margin: 5px 0;
            border: 1px solid #ddd;
            border-radius: 4px;
            box-sizing: border-box;
        }
        .form-group {
            margin-bottom: 15px;
        }
        label {
            display: block;
            margin-bottom: 5px;
            font-weight: bold;
        }
    </style>
</head>
<body>
    <div class="container">
        <h1>物联网卡年费订单测试</h1>
        
        <!-- 配置设置 -->
        <div class="test-section">
            <h3>🔧 API 配置</h3>
            <div class="form-group">
                <label for="baseUrl">API 基础地址:</label>
                <input type="text" id="baseUrl" value="http://localhost:7001/api" placeholder="http://localhost:7001/api">
            </div>
            <div class="form-group">
                <label for="token">认证Token:</label>
                <input type="text" id="token" placeholder="请输入认证Token">
            </div>
        </div>

        <!-- 计费配置测试 -->
        <div class="test-section">
            <h3>💰 计费配置测试</h3>
            <button onclick="getBillingConfig()">获取物联网卡计费配置</button>
            <button onclick="initBillingConfig()">初始化计费配置</button>
            <div id="billingResult" class="result info" style="display:none;"></div>
        </div>

        <!-- 物联网卡年费订单测试 -->
        <div class="test-section">
            <h3>📱 物联网卡年费订单测试</h3>
            <button onclick="createIotYearOrder()">创建物联网卡年费订单</button>
            <button onclick="getOrderList()">获取订单列表</button>
            <div id="orderResult" class="result info" style="display:none;"></div>
        </div>

        <!-- 错误场景测试 -->
        <div class="test-section">
            <h3>⚠️ 错误场景测试</h3>
            <button onclick="testWithoutToken()">无Token测试</button>
            <button onclick="testWithInvalidToken()">无效Token测试</button>
            <div id="errorResult" class="result info" style="display:none;"></div>
        </div>
    </div>

    <script>
        // 获取API基础配置
        function getApiConfig() {
            const baseUrl = document.getElementById('baseUrl').value;
            const token = document.getElementById('token').value;
            return { baseUrl, token };
        }

        // 通用API请求函数
        async function apiRequest(url, options = {}) {
            const { baseUrl, token } = getApiConfig();
            const fullUrl = `${baseUrl}${url}`;
            
            const defaultOptions = {
                method: 'GET',
                headers: {
                    'Content-Type': 'application/json',
                    ...(token && { 'Authorization': `Bearer ${token}` })
                }
            };

            const finalOptions = { ...defaultOptions, ...options };
            
            try {
                console.log(`请求: ${finalOptions.method} ${fullUrl}`);
                if (finalOptions.body) {
                    console.log('请求体:', finalOptions.body);
                }
                
                const response = await fetch(fullUrl, finalOptions);
                const data = await response.json();
                
                console.log('响应:', data);
                return { success: response.ok, data, status: response.status };
            } catch (error) {
                console.error('请求错误:', error);
                return { success: false, error: error.message };
            }
        }

        // 显示结果
        function showResult(elementId, result, type = 'info') {
            const element = document.getElementById(elementId);
            element.style.display = 'block';
            element.className = `result ${type}`;
            
            if (result.success) {
                element.textContent = `✅ 请求成功\n${JSON.stringify(result.data, null, 2)}`;
                element.className = 'result success';
            } else {
                element.textContent = `❌ 请求失败\n状态码: ${result.status || 'N/A'}\n错误: ${result.error || JSON.stringify(result.data, null, 2)}`;
                element.className = 'result error';
            }
        }

        // 获取物联网卡计费配置
        async function getBillingConfig() {
            const result = await apiRequest('/admin/billing/config/list?serviceType=iot_card');
            showResult('billingResult', result);
        }

        // 初始化计费配置
        async function initBillingConfig() {
            const result = await apiRequest('/admin/billing/config/init', {
                method: 'POST'
            });
            showResult('billingResult', result);
        }

        // 创建物联网卡年费订单
        async function createIotYearOrder() {
            const result = await apiRequest('/app/pay/order/iotYear', {
                method: 'POST',
                body: JSON.stringify({})
            });
            showResult('orderResult', result);
        }

        // 获取订单列表
        async function getOrderList() {
            const result = await apiRequest('/app/pay/order/list?page=1&size=10');
            showResult('orderResult', result);
        }

        // 无Token测试
        async function testWithoutToken() {
            const { baseUrl } = getApiConfig();
            const result = await apiRequest('/app/pay/order/iotYear', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({})
            });
            showResult('errorResult', result);
        }

        // 无效Token测试
        async function testWithInvalidToken() {
            const { baseUrl } = getApiConfig();
            const result = await apiRequest('/app/pay/order/iotYear', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'Authorization': 'Bearer invalid_token_123'
                },
                body: JSON.stringify({})
            });
            showResult('errorResult', result);
        }

        // 页面加载完成后的初始化
        document.addEventListener('DOMContentLoaded', function() {
            console.log('物联网卡年费订单测试页面已加载');
            
            // 显示使用说明
            const info = document.createElement('div');
            info.className = 'result info';
            info.innerHTML = `
📋 使用说明：
1. 首先配置正确的API基础地址和认证Token
2. 测试计费配置功能，确保物联网卡年费配置存在
3. 测试创建物联网卡年费订单功能
4. 查看订单列表验证订单是否创建成功
5. 测试错误场景，验证错误处理是否正确

🔍 主要修复内容：
- 修复了计费配置查询逻辑，使用serviceType而不是固定ID
- 添加了完善的错误处理和参数验证
- 增强了用户会话验证
- 改进了错误信息提示
            `;
            document.querySelector('.container').insertBefore(info, document.querySelector('.test-section'));
        });
    </script>
</body>
</html>